#!/bin/sh /etc/rc.common

# Copyright (C) 2018 max0y <askmaxwork@gmail.com>
# Licensed to the public under the GNU General Public License v3.

START=65

run_cd8021x()
{
    local enable
    config_get_bool enable $1 enable
    
    if [ $enable ]; then
        local username
        local password
        local ifname
        local eap
        
        config_get username $1 username
        config_get password $1 password
        config_get ifname $1 ifname
        config_get eap $1 eap
        
        killall wpa_supplicant
        echo -e "ctrl_interface=/var/run/wpa_supplicant\nctrl_interface_group=root\nap_scan=0\nnetwork={\nkey_mgmt=IEEE8021X\neap=$eap\nidentity=\"$username\"\npassword=\"$password\"" > /tmp/cd8021x.conf
        case "$eap" in
            "MD5")
                echo -e "eapol_flags=0\n}" >> /tmp/cd8021x.conf
                ;;
            "PEAP")
                echo -e "anonymous_identity=\"$username\"\npairwise=CCMP TKIP\nphase2=\"auth=MSCHAPV2\"\npriority=2\n}" >> /tmp/cd8021x.conf
                ;;
            "MSCHAPV2")
                echo -e "eapol_flags=0\nphase1=\"peaplabel=1\"\nphase2=\"auth=MSCHAPV2\"\n}" >> /tmp/cd8021x.conf
                ;;
            *)
        esac

        wpa_supplicant -B -c /tmp/cd8021x.conf -i$ifname -Dwired
        
        echo "cd802.1x client has started."
    fi
}

start()
{
    config_load cd8021x
    config_foreach run_cd8021x login
}

stop()
{
    killall wpa_supplicant    
    echo "cd802.1x client has stoped."
}
